import React, { useState } from 'react';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { Card } from 'antd'
import { SortableItem } from '@/components/SortableItem';
import { DragOutlined } from "@ant-design/icons"

function SortContent({ items, setItems }) {

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
    >
      <SortableContext
        items={items.map(it => it.key)}
        strategy={verticalListSortingStrategy}
      >
        {items.map(it => <SortableItem key={it.key} id={it.key}>
          <Card size='small' style={{ cursor: "move", width: "100%", marginBottom: 10, padding: 16 }} >
            <DragOutlined style={{marginRight:12}}></DragOutlined>
            {it.tab}
          </Card>
        </SortableItem>)}
      </SortableContext>
    </DndContext>
  );

  function handleDragEnd(event) {
    const { active, over } = event;
    if (active.id !== over.id) {
      setItems((items) => {
        const keyarr = items.map(it => it.key);
        const oldIndex = keyarr.indexOf(active.id);
        const newIndex = keyarr.indexOf(over.id);
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  }
}

export default SortContent;